define(['store', 'angular', 'angular-cache', 'uiRouter', 'config', 'filters/filters',
        'services/services', 'animations/animations', 'directives/directives', 'controllers/controllers',
        'ionicAngular'],

    function (store, angular) {
        'use strict';

        var app = angular.module('app', ['angular-cache','ngCordova', 'ionic','app.controllers','app.filters',
            'app.services','app.animations','app.directives','app.config','ui.router',
            'door3.css', 'ngmodel.format', 'platanus.keepValues', 'highcharts-ng',
            'ngCookies', 'offline']);
        app.constant('$ionicLoadingConfig', {
            template: '<img src="../img/ripple.svg" style="padding:0;width:40px;height:40px;">',//动画模板
            showBackdrop: true                 //是否显示蒙层
        });


        app.factory('$exceptionHandler', function () {
            return function (exception, cause) {
                exception.message += ' (caused by "' + cause + '")';
                if(typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_reportError",{error: exception.message.toString()} ,null,null);
                }
                throw exception;
            };
        });

        app.factory('UserInterceptor', ["$q","$rootScope","CacheFactory", function ($q,$rootScope, CacheFactory) {
            return {
                request:function(config){
                    var UUID =  store.get('UUID');
                    if(UUID) {
                        config.headers["UUID"] = UUID;
                    }
                    var userCache = CacheFactory.get('UserCache');
                    var user = userCache.get('user');
                    if(user) {
                        config.headers["TOKEN"] = user.token;
                    }
                    return config;
                },
                // optional method
                'response': function(response) {
                    var data = response.data;
                    if(data){
                        // 判断错误码，如果是未登录
                        if(data["error_no"] == "AH-10001"){
                            // 清空用户本地token存储的信息，如果
                            var userCache = CacheFactory.get('UserCache');
                            userCache.remove('user');
                            // 全局事件，方便其他view获取该事件，并给以相应的提示或处理
                            $rootScope.$emit("userIntercepted","sessionOut",response);
                            return $q.reject(response);
                        }
                        // 开户会话过期
                        if(data["error_no"] == "AH-10002"){
                            //清空本地开户用户信息
                            var userCache = CacheFactory.get('UserCache');
                            userCache.remove('user');
                            $rootScope.$emit("openUserIntercepted","sessionOut",response);
                            return $q.reject(response);
                        }
                    }
                    return response;
                },
                responseError: function (response) {
                    if(response.status == "0") {
                        TF.Bubble.show("请求超时，请稍后再试");
                    }
                    if(response.status != "200") {
                        var type = response.config.method;
                        var url = response.config.url;
                        var status = response.status;
                        var errorInfo = type + ":" + url + ":"  + status;
                        if(typeof Messenger != 'undefined') {
                            Messenger.sendMsg("ym_reportError",{error: errorInfo} ,null,null);
                        }
                    }
                    if(response.status == "404"){}
                    var data = response.data;
                    if(data){
                        // 判断错误码，如果是未登录
                        if(data["error_no"] == "AH-10001"){
                            // 清空用户本地token存储的信息，如果
                            store.remove('user');
                            // 全局事件，方便其他view获取该事件，并给以相应的提示或处理
                            $rootScope.$emit("userIntercepted","sessionOut",response);
                        }
                        // 开户会话过期
                        if(data["error_no"] == "AH-10002"){
                            //清空本地开户用户信息
                            store.remove('openUser');
                            $rootScope.$emit("openUserIntercepted","sessionOut",response);
                            return $q.reject(response);
                        }
                    }
                    return $q.reject(response);
                }
            };
        }]);

        app.config(function ($httpProvider, $ionicConfigProvider) {
            $ionicConfigProvider.platform.ios.tabs.position('bottom');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.scrolling.jsScrolling(true);
            $ionicConfigProvider.views.transition("none");
            $ionicConfigProvider.views.swipeBackEnabled(false);

            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            $httpProvider.interceptors.push('UserInterceptor');

            //Override $http service's default transformRequest
            $httpProvider.defaults.transformRequest = [function(data) {

                var param = function(obj) {
                    var query = '';
                    var name, value, fullSubName, subName, subValue, innerObj, i;
                    for (name in obj) {
                        value = obj[name];
                        if (value instanceof Array) {
                            for (i = 0; i < value.length; ++i) {
                                subValue = value[i];
                                fullSubName = name + '[' + i + ']';
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        } else if (value instanceof Object) {
                            for (subName in value) {
                                subValue = value[subName];
                                fullSubName = name + '[' + subName + ']';
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        } else if (value !== undefined && value !== null) {
                            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                        }
                    }
                    return query.length ? query.substr(0, query.length - 1) : query;
                };

                return angular.isObject(data) && String(data) !== '[object File]'
                    ? param(data) : data;
            }];

            $httpProvider.defaults.transformResponse.push(function(data){
                if(data && angular.isObject(data) && data.error_no == 0 && data.data) {
                    var result = data.data;
                    if (result) {
                        if (angular.isArray(result)) {
                            var length = result.length;
                            for (var i = 0; i < length; i++) {
                                changeObjectWithImg(result[i]);
                            }
                        } else {
                            changeObjectWithImg(result);
                        }
                    }
                }
                return data;
            });

            function changeObjectWithImg(o){
                if(o && angular.isObject(o)) {
                    for(var j in o){
                        if(isImgUrl(o[j])) {
                            o[j] = getImgUrl(o[j]);
                        }
                    }
                }
                return o;
            }

            function isImgUrl(path){
                if(path && angular.isString(path)) {
                    var index = path.lastIndexOf("\\");
                    var filename=path.substr(index + 1);
                    var patn = /\.jpg$|\.jpeg$|\.gif$|\.png$/i;
                    return patn.test(filename);
                }
                return false;
            }

            function getImgUrl(webUrl){ //存储图片
                var localUrl = store.get(webUrl);
                if(localUrl && checkImgExists(localUrl)){
                    return localUrl;
                } else{
                    store.remove(webUrl);
                }
                if (typeof(FileLoad) != "undefined") {
                    FileLoad.fileLoadPath(webUrl, function(data){
                        if(data) {
                            localUrl = data;
                            store.set(webUrl, localUrl);
                        }
                    });
                }
                return webUrl;
            }

            function checkImgExists(localUrl) {
                var ImgObj = new Image(); //判断图片是否存在
                ImgObj.src = localUrl;
                if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        return app;
    });